leds.pl 8.4 KB

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