leds.pl 8.5 KB

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