leds.pl 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Select;
  5. use Math::Random;
  6. use IO::Socket::UNIX;
  7. use File::Temp qw( tempfile );
  8. use Time::HiRes qw( usleep );
  9. # Prototypes
  10. sub dim($);
  11. sub red_alert();
  12. sub red_flash();
  13. # Effects states
  14. my %EFFECTS = (
  15. 'RED_ALERT' => \&red_alert,
  16. 'RED_FLASH' => \&red_flash,
  17. );
  18. # User config
  19. my $COLOR_TIMEOUT = 30;
  20. my $COLOR_TIME_MIN = int($COLOR_TIMEOUT / 2);
  21. my %COLOR_VAR = (
  22. 'PLAY' => 0.50,
  23. 'PLAY_HIGH' => 0.50,
  24. 'PAUSE' => 0.65,
  25. 'MOTION' => 0.25,
  26. );
  27. my %DIM = (
  28. 'OFF' => [
  29. # Handled by rope.pl
  30. ],
  31. 'PLAY' => [
  32. { 'channel' => 13, 'value' => 10, 'time' => 500 },
  33. { 'channel' => 14, 'value' => 12, 'time' => 500 },
  34. { 'channel' => 15, 'value' => 8, 'time' => 500 },
  35. ],
  36. 'PLAY_HIGH' => [
  37. { 'channel' => 13, 'value' => 64, 'time' => 1000, 'delay' => 3000 },
  38. { 'channel' => 14, 'value' => 73, 'time' => 1000, 'delay' => 1500 },
  39. { 'channel' => 15, 'value' => 76, 'time' => 1000, 'delay' => 0 },
  40. ],
  41. 'PAUSE' => [
  42. { 'channel' => 13, 'value' => 96, 'time' => 3000, 'delay' => 3000 },
  43. { 'channel' => 14, 'value' => 109, 'time' => 3000, 'delay' => 0 },
  44. { 'channel' => 15, 'value' => 114, 'time' => 3000, 'delay' => 7000 },
  45. ],
  46. 'MOTION' => [
  47. { 'channel' => 13, 'value' => 144, 'time' => 1000 },
  48. { 'channel' => 14, 'value' => 164, 'time' => 1000 },
  49. { 'channel' => 15, 'value' => 172, 'time' => 1000 },
  50. ],
  51. );
  52. # App config
  53. my $SOCK_TIMEOUT = 5;
  54. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  55. chomp($TEMP_DIR);
  56. my $DATA_DIR = $TEMP_DIR . 'plexMonitor/';
  57. my $DMX_SOCK = $DATA_DIR . 'DMX.socket';
  58. my $SUB_SOCK = $DATA_DIR . 'STATE.socket';
  59. my $STATE_SOCK = $DATA_DIR . 'LED.socket';
  60. my $MAX_CMD_LEN = 1024;
  61. my $PUSH_TIMEOUT = 20;
  62. my $PULL_TIMEOUT = 60;
  63. # Reset the push timeout if the color timeout is longer
  64. if ($PUSH_TIMEOUT < $COLOR_TIMEOUT) {
  65. $PUSH_TIMEOUT = $COLOR_TIMEOUT;
  66. }
  67. # Debug
  68. my $DEBUG = 0;
  69. if ($ENV{'DEBUG'}) {
  70. $DEBUG = 1;
  71. }
  72. # Command-line arguments
  73. my ($DELAY) = @ARGV;
  74. if (!$DELAY) {
  75. $DELAY = $PULL_TIMEOUT / 2;
  76. if ($DELAY > $COLOR_TIMEOUT / 2) {
  77. $DELAY = $COLOR_TIMEOUT / 2;
  78. }
  79. }
  80. # Sanity check
  81. if (!-d $DATA_DIR || !-S $DMX_SOCK || !-S $SUB_SOCK) {
  82. die("Bad config\n");
  83. }
  84. # State socket init
  85. if (-e $STATE_SOCK) {
  86. unlink($STATE_SOCK);
  87. }
  88. my $state_fh = IO::Socket::UNIX->new(
  89. 'Local' => $STATE_SOCK,
  90. 'Type' => SOCK_DGRAM
  91. ) or die('Unable to open socket: ' . $STATE_SOCK . ": ${@}\n");
  92. my $select = IO::Select->new($state_fh)
  93. or die('Unable to select socket: ' . $STATE_SOCK . ": ${!}\n");
  94. # DMX socket init
  95. my $dmx_fh = IO::Socket::UNIX->new(
  96. 'Peer' => $DMX_SOCK,
  97. 'Type' => SOCK_DGRAM,
  98. 'Timeout' => $SOCK_TIMEOUT
  99. ) or die('Unable to open socket: ' . $DMX_SOCK . ": ${@}\n");
  100. # Subscribe to state updates
  101. my $sub_fh = IO::Socket::UNIX->new(
  102. 'Peer' => $SUB_SOCK,
  103. 'Type' => SOCK_DGRAM,
  104. 'Timeout' => $SOCK_TIMEOUT
  105. ) or die('Unable to open socket: ' . $SUB_SOCK . ": ${@}\n");
  106. $sub_fh->send($STATE_SOCK)
  107. or die('Unable to subscribe: ' . $! . "\n");
  108. shutdown($sub_fh, 2);
  109. undef($sub_fh);
  110. # State
  111. my $state = 'INIT';
  112. my $stateLast = $state;
  113. my %exists = ();
  114. my %existsLast = %exists;
  115. my $pushLast = 0;
  116. my $pullLast = time();
  117. my @COLOR = ();
  118. my $colorChange = time();
  119. # Always force lights out at launch
  120. dim({ 'channel' => 13, 'value' => 0, 'time' => 0 });
  121. dim({ 'channel' => 14, 'value' => 0, 'time' => 0 });
  122. dim({ 'channel' => 15, 'value' => 0, 'time' => 0 });
  123. # Loop forever
  124. while (1) {
  125. # Record the last state/exists data for diffs/resets
  126. $stateLast = $state;
  127. %existsLast = %exists;
  128. # Set anywhere to force an update this cycle
  129. my $forceUpdate = 0;
  130. # State is calculated; use newState to gather data
  131. my $newState = $state;
  132. # Wait for state updates
  133. my @ready_clients = $select->can_read($DELAY);
  134. foreach my $fh (@ready_clients) {
  135. # Grab the inbound text
  136. my $text = undef();
  137. $fh->recv($text, $MAX_CMD_LEN);
  138. # Parse the string
  139. %exists = ();
  140. my ($cmdState, $exists_text) = $text =~ /^(\w+)(?:\s+\(([^\)]+)\))?/;
  141. if (!defined($cmdState)) {
  142. print STDERR 'State parse error: ' . $text . "\n";
  143. next;
  144. }
  145. if (defined($exists_text)) {
  146. foreach my $exists (split(/\s*,\s*/, $exists_text)) {
  147. my ($name, $value) = $exists =~ /(\w+)\:(0|1)/;
  148. if (!defined($name) || !defined($value)) {
  149. print STDERR 'State parse error (exists): ' . $text . "\n";
  150. next;
  151. }
  152. $exists{$name} = $value;
  153. }
  154. }
  155. if ($DEBUG) {
  156. my @exists_tmp = ();
  157. foreach my $key (keys(%exists)) {
  158. push(@exists_tmp, $key . ':' . $exists{$key});
  159. }
  160. print STDERR 'Got state: ' . $cmdState . ' (' . join(', ', @exists_tmp) . ")\n";
  161. }
  162. # Translate INIT to OFF
  163. if ($cmdState eq 'INIT') {
  164. $cmdState = 'OFF';
  165. }
  166. # Only accept valid states
  167. if (!defined($DIM{$cmdState}) && !defined($EFFECTS{$cmdState})) {
  168. print STDERR 'Invalid state: ' . $cmdState . "\n";
  169. next;
  170. }
  171. # Propogate the most recent command state
  172. $newState = $cmdState;
  173. $pullLast = time();
  174. }
  175. # Special handling for effects states
  176. if (defined($EFFECTS{$newState})) {
  177. # Dispatch the handler
  178. $EFFECTS{$newState}->();
  179. # Force an update back to the original state
  180. $newState = $stateLast;
  181. %exists = %existsLast;
  182. @COLOR = ();
  183. $colorChange = time() + $COLOR_TIME_MIN;
  184. $forceUpdate = 1;
  185. }
  186. # Calculate the new state
  187. if ($exists{'LIGHTS'}) {
  188. if ($newState eq 'PLAY') {
  189. $newState = 'PLAY_HIGH';
  190. }
  191. } else {
  192. if ($newState eq 'PLAY_HIGH') {
  193. $newState = 'PLAY';
  194. }
  195. }
  196. $state = $newState;
  197. if ($DEBUG) {
  198. print STDERR 'State: ' . $state . "\n";
  199. }
  200. # Color changes
  201. if ($COLOR_VAR{$state} && time() - $colorChange > $COLOR_TIMEOUT) {
  202. @COLOR = ();
  203. # Grab the default (white) data
  204. my $lums = 0;
  205. foreach my $data (@{ $DIM{$state} }) {
  206. $lums += $data->{'value'};
  207. }
  208. my $numChans = scalar(@{ $DIM{$state} });
  209. my $max = $lums / $numChans;
  210. # Pick the change interval
  211. my $time = int((rand($COLOR_TIMEOUT - $COLOR_TIME_MIN) + $COLOR_TIME_MIN) * 1000);
  212. # Assign each channel
  213. my @vals = random_normal($numChans, $max, $max * $COLOR_VAR{$state});
  214. foreach my $data (@{ $DIM{$state} }) {
  215. my $color = pop(@vals);
  216. $color = int($color);
  217. if ($color < 0) {
  218. $color = 0;
  219. } elsif ($color > 255) {
  220. $color = 255;
  221. }
  222. push(@COLOR, { 'channel' => $data->{'channel'}, 'value' => $color, 'time' => $time });
  223. }
  224. # Update
  225. $forceUpdate = 1;
  226. $colorChange = time();
  227. if ($DEBUG) {
  228. print STDERR "New color\n";
  229. }
  230. }
  231. # Force updates on a periodic basis
  232. if (time() - $pushLast > $PUSH_TIMEOUT) {
  233. $forceUpdate = 1;
  234. }
  235. # Die if we don't see regular updates
  236. if (time() - $pullLast > $PULL_TIMEOUT) {
  237. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  238. }
  239. # Force updates on any state change
  240. if ($stateLast ne $state) {
  241. $forceUpdate = 1;
  242. # Reset the color change sequence, so we always spend 1 cycle at white
  243. @COLOR = ();
  244. $colorChange = time() + $COLOR_TIME_MIN;
  245. }
  246. # Update the lighting
  247. if ($forceUpdate) {
  248. # Select a data set (color or standard)
  249. my @data_set = ();
  250. if (scalar(@COLOR)) {
  251. @data_set = @COLOR;
  252. } else {
  253. @data_set = @{ $DIM{$state} };
  254. }
  255. # Debug
  256. if ($DEBUG) {
  257. my $sum = 0;
  258. print STDERR 'State: ' . $stateLast . ' => ' . $state . ' (Color: ' . scalar(@COLOR) . ")\n";
  259. foreach my $data (@{ $DIM{$state} }) {
  260. $sum += $data->{'value'};
  261. my $delay = '';
  262. if ($data->{'delay'}) {
  263. $delay = ' (Delay: ' . $data->{'delay'} . ')';
  264. }
  265. print STDERR "\t" . $data->{'channel'} . ' => ' . $data->{'value'} . ' @ ' . $data->{'time'} . $delay . "\n";
  266. }
  267. print STDERR "\tTotal: " . $sum . "\n";
  268. }
  269. # Send the dim command
  270. my @values = ();
  271. foreach my $data (@data_set) {
  272. dim($data);
  273. push(@values, $data->{'channel'} . ' => ' . $data->{'value'} . ' @ ' . $data->{'time'});
  274. }
  275. # Save the state and value to disk
  276. my ($fh, $tmp) = tempfile($DATA_DIR . 'LED.XXXXXXXX', 'UNLINK' => 0);
  277. print $fh 'State: ' . $state . "\n" . join("\n", @values) . "\n";
  278. close($fh);
  279. rename($tmp, $DATA_DIR . 'LED');
  280. # Update the push time
  281. $pushLast = time();
  282. }
  283. }
  284. # Send the command
  285. sub dim($) {
  286. my ($args) = @_;
  287. if (!defined($args->{'delay'})) {
  288. $args->{'delay'} = 0;
  289. }
  290. if (!defined($args->{'channel'}) || !defined($args->{'time'}) || !defined($args->{'value'})) {
  291. die('Invalid command for socket: ' . join(', ', keys(%{$args})) . ': ' . join(', ', values(%{$args})) . "\n");
  292. }
  293. my $cmd = join(':', $args->{'channel'}, int($args->{'time'}), int($args->{'value'}), int($args->{'delay'}));
  294. $dmx_fh->send($cmd)
  295. or die('Unable to write command to socket: ' . $DMX_SOCK . ': ' . $cmd . ": ${!}\n");
  296. }
  297. # ======================================
  298. # Effects routines
  299. # These are blocking, so be careful
  300. # ======================================
  301. sub red_alert() {
  302. my $ramp = 500;
  303. my @sound = ('afplay', '/mnt/media/Sounds/DMX/Red Alert.mp3');
  304. my $sleep = $ramp;
  305. my @other = ();
  306. push(@other, { 'channel' => 13, 'value' => 0, 'time' => 0 });
  307. push(@other, { 'channel' => 15, 'value' => 0, 'time' => 0 });
  308. foreach my $data (@other) {
  309. dim($data);
  310. }
  311. my %high = ('channel' => 14, 'value' => 255, 'time' => $ramp);
  312. my %low = %high;
  313. $low{'value'} = 64;
  314. dim(\%high);
  315. system(@sound);
  316. dim(\%low);
  317. usleep($sleep * 1000);
  318. dim(\%high);
  319. system(@sound);
  320. dim(\%low);
  321. usleep($sleep * 1000);
  322. dim(\%high);
  323. system(@sound);
  324. dim(\%low);
  325. usleep($sleep * 1000);
  326. }
  327. sub red_flash() {
  328. }