state.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Select;
  5. use File::Basename;
  6. use File::Temp qw( tempfile );
  7. use Sys::Hostname;
  8. use IPC::System::Simple qw( system capture );
  9. # Local modules
  10. use Cwd qw(abs_path);
  11. use File::Basename qw(dirname);
  12. use lib dirname(abs_path($0));
  13. use DMX;
  14. # Prototypes
  15. sub mtime($);
  16. # User config
  17. my %DISPLAY_DEVS = ('TV' => 1, 'PROJECTOR' => 1);
  18. my $DISPLAY = undef();
  19. my $STATE_TIMEOUT = 180;
  20. my $EXISTS_TIMEOUT = 900;
  21. my %MON_FILES = ();
  22. # Host-specific config
  23. # This is necessary to avoid contention on shared disks
  24. my $HOST = Sys::Hostname::hostname();
  25. if ($HOST =~ /loki/i) {
  26. # Ensure the media path is available before we get going
  27. my $MEDIA_PATH = undef();
  28. {
  29. my $mount = $ENV{'HOME'} . '/bin/video/mediaPath';
  30. $MEDIA_PATH = capture($mount);
  31. }
  32. if (!$MEDIA_PATH || !-d $MEDIA_PATH) {
  33. die("Unable to access media path\n");
  34. }
  35. # Garage door opener
  36. $MON_FILES{ $MEDIA_PATH . '/DMX/cmd/GARAGE_CMD' } = 'EXISTS-VALUE-CLEAR';
  37. }
  38. # Available state files
  39. {
  40. # Plex
  41. $MON_FILES{'PLEX'} = 'NONE';
  42. $MON_FILES{'GUI'} = 'NONE';
  43. $MON_FILES{'PLAYING'} = 'PLAYING';
  44. # RiffTrax
  45. $MON_FILES{'RIFF'} = 'VALUE-NOUPDATE';
  46. # Motion detection
  47. $MON_FILES{'MOTION'} = 'MTIME';
  48. $MON_FILES{'NO_MOTION'} = 'EXISTS-NOUPDATE';
  49. # Projector
  50. $MON_FILES{'PROJECTOR'} = 'STATUS';
  51. $MON_FILES{'PROJECTOR_COLOR'} = 'VALUE';
  52. $MON_FILES{'PROJECTOR_INPUT'} = 'VALUE';
  53. $MON_FILES{'PROJECTOR_LAMP'} = 'VALUE';
  54. # Amplifier
  55. $MON_FILES{'AMPLIFIER'} = 'STATUS';
  56. $MON_FILES{'AMPLIFIER_VOL'} = 'VALUE';
  57. $MON_FILES{'AMPLIFIER_MODE'} = 'VALUE';
  58. $MON_FILES{'AMPLIFIER_INPUT'} = 'VALUE';
  59. $MON_FILES{'AUDIO_AMP'} = 'EXISTS-ON';
  60. $MON_FILES{'STEREO_CMD'} = 'EXISTS-ON';
  61. # A/V Effects
  62. $MON_FILES{'LIGHTS'} = 'EXISTS-TIMEOUT';
  63. $MON_FILES{'BRIGHT'} = 'EXISTS-TIMEOUT';
  64. $MON_FILES{'RAVE'} = 'EXISTS';
  65. $MON_FILES{'EFFECT'} = 'EXISTS';
  66. # Equipment
  67. $MON_FILES{'FAN_CMD'} = 'EXISTS-ON';
  68. # OS State
  69. $MON_FILES{'FRONT_APP'} = 'VALUE-NOUPDATE';
  70. $MON_FILES{'COLOR'} = 'VALUE-NOUPDATE';
  71. $MON_FILES{'AUDIO'} = 'VALUE-NOUPDATE';
  72. $MON_FILES{'AUDIO_STATE'} = 'VALUE-NOUPDATE';
  73. # TV
  74. $MON_FILES{'TV'} = 'STATUS';
  75. $MON_FILES{'TV_VOL'} = 'VALUE';
  76. }
  77. my %EXTRAS = (
  78. 'PLAYING' => {
  79. 'URL' => qr/^file:(.+)$/m,
  80. 'YEAR' => qr/^year:(\d+)/m,
  81. 'SERIES' => qr/^showtitle:(.+)$/m,
  82. 'SEASON' => qr/^season:(\d+)/m,
  83. 'EPISODE' => qr/^episode:(\d+)/m,
  84. 'TITLE' => qr/^title:(.+)$/m,
  85. 'LENGTH' => qr/^duration:(\d+)/m,
  86. 'POSITION' => qr/^time:(\d+(?:\.\d+)?)/m,
  87. 'TYPE' => qr/^type:(.+)$/m,
  88. 'IMAGE' => qr/^fanart:(.+)$/m,
  89. 'THUMB' => qr/^thumbnail:(.+)$/m,
  90. 'ALBUM' => qr/^album:(.+)$/m,
  91. 'ARTIST' => qr/^artist:(.+)$/m,
  92. 'SELECTION' => qr/^selection:(.+)$/m,
  93. 'WINDOW' => qr/^window:(.+)$/m,
  94. 'WINDOWID' => qr/^windowid:(\d+)/m,
  95. }
  96. );
  97. # App config
  98. my $SOCK_TIMEOUT = 5;
  99. my $DATA_DIR = DMX::dataDir();
  100. my $CMD_FILE = 'STATE';
  101. my $MAX_CMD_LEN = 4096;
  102. my $RESET_CMD = $ENV{'HOME'} . '/bin/video/dmx/reset.sh';
  103. my $PUSH_TIMEOUT = 20;
  104. # Debug
  105. my $DEBUG = 0;
  106. if ($ENV{'DEBUG'}) {
  107. $DEBUG = 1;
  108. }
  109. # Command-line arguments
  110. my ($DELAY) = @ARGV;
  111. if (!$DELAY) {
  112. $DELAY = 0.5;
  113. }
  114. # Socket init
  115. my $select = DMX::stateSocket($CMD_FILE);
  116. # Add the extras to the main file list
  117. foreach my $file (keys(%EXTRAS)) {
  118. if (exists($MON_FILES{$file})) {
  119. foreach my $extra (keys(%{ $EXTRAS{$file} })) {
  120. $MON_FILES{ $file . '_' . $extra } = 'NONE';
  121. }
  122. }
  123. }
  124. # Init the file tracking structure
  125. my %files = ();
  126. foreach my $name (keys(%MON_FILES)) {
  127. my %file = (
  128. 'name' => basename($name),
  129. 'type' => $MON_FILES{$name},
  130. 'path' => $DATA_DIR . $name,
  131. 'update' => 0,
  132. 'value' => 0,
  133. 'last' => 0,
  134. );
  135. # Allow absolute paths to override the $DATA_DIR path
  136. if ($name =~ /^\//) {
  137. $file{'path'} = $name;
  138. }
  139. # Record the directory name for folder monitoring
  140. $file{'dir'} = dirname($file{'path'});
  141. # Set the attribute bits, for use in later update handling logic
  142. my %attr = (
  143. 'available' => 0,
  144. 'status' => 0,
  145. 'exists' => 0,
  146. 'value' => 0,
  147. 'clear' => 0,
  148. 'clear_off' => 0,
  149. 'mtime' => 0,
  150. 'playing' => 0,
  151. 'no_update' => 0,
  152. );
  153. if ($file{'type'} =~ /\bSTATUS\b/i) {
  154. $attr{'status'} = 1;
  155. }
  156. if ($file{'type'} =~ /\bEXISTS\b/i) {
  157. $attr{'exists'} = 1;
  158. }
  159. if ($file{'type'} =~ /\bVALUE\b/i) {
  160. $attr{'value'} = 1;
  161. }
  162. if ($file{'type'} =~ /\bCLEAR\b/i) {
  163. $attr{'clear'} = 1;
  164. }
  165. if ($file{'type'} =~ /\bON\b/i) {
  166. $attr{'clear_off'} = 1;
  167. }
  168. if ($file{'type'} =~ /\bTIMEOUT\b/i) {
  169. $attr{'clear_timeout'} = 1;
  170. }
  171. if ($file{'type'} =~ /\bMTIME\b/i) {
  172. $attr{'mtime'} = 1;
  173. }
  174. if ($file{'type'} =~ /\bPLAYING\b/i) {
  175. $attr{'playing'} = 1;
  176. }
  177. if ($file{'type'} =~ /\bNOUPDATE\b/i) {
  178. $attr{'no_update'} = 1;
  179. }
  180. # Cross-match some data types for easy of use
  181. if ($attr{'value'} || $attr{'playing'}) {
  182. $attr{'status'} = 1;
  183. }
  184. if ($attr{'status'} || $attr{'exists'}) {
  185. $attr{'mtime'} = 1;
  186. }
  187. # Push ATTR into the file hash
  188. $file{'attr'} = \%attr;
  189. # Push FILE into the files hash
  190. $files{$name} = \%file;
  191. }
  192. # Delete any existing input files, to ensure our state is reset
  193. foreach my $file (values(%files)) {
  194. if (-e $file->{'path'}) {
  195. if ($DEBUG) {
  196. print STDERR 'Deleting ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  197. }
  198. unlink($file->{'path'});
  199. }
  200. }
  201. # Reset all dependents at starts
  202. system($RESET_CMD);
  203. # Subscribers
  204. my @subscribers = ();
  205. # State
  206. my $state = 'INIT';
  207. my $stateLast = $state;
  208. my $status = '';
  209. my $statusLast = $status;
  210. my $updateLast = 0;
  211. my $timeSinceUpdate = 0;
  212. my $pushLast = 0;
  213. # Loop forever
  214. while (1) {
  215. # Provide a method to force updates even when the state does not change
  216. my $update = 0;
  217. # Check for queued commands
  218. my @ready_clients = $select->can_read($DELAY);
  219. foreach my $fh (@ready_clients) {
  220. # Grab the inbound text
  221. my $path = undef();
  222. $fh->recv($path, $MAX_CMD_LEN);
  223. $path =~ s/^\s+//;
  224. $path =~ s/\s+$//;
  225. $path =~ s/\W/_/g;
  226. if ($DEBUG) {
  227. print STDERR 'Got path: ' . $path . "\n";
  228. }
  229. # Open the new socket
  230. my $sub = eval { DMX::clientSock($path); };
  231. if (!$sub) {
  232. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  233. next;
  234. }
  235. # Add the socket to our subscriber list
  236. my %tmp = (
  237. 'path' => $path,
  238. 'socket' => $sub,
  239. );
  240. push(@subscribers, \%tmp);
  241. # Force an update
  242. $update = 1;
  243. }
  244. # Use opendir/readdir in each folder to ensure fresh results
  245. my %folders = ();
  246. foreach my $file (values(%files)) {
  247. if (!$folders{ $file->{'dir'} }) {
  248. my $dh = undef();
  249. opendir($dh, $file->{'dir'})
  250. or die('Unable to open directory: ' . $file->{'dir'});
  251. if ($DEBUG) {
  252. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  253. }
  254. my @files = readdir($dh);
  255. closedir($dh);
  256. $folders{ $file->{'dir'} } = 1;
  257. }
  258. }
  259. # Monitor files of all types
  260. foreach my $file (values(%files)) {
  261. # Skip "NONE" files -- they are data stores handled in other actions
  262. if ($file->{'type'} eq 'NONE') {
  263. next;
  264. }
  265. # Always record the previous status and clear the new one
  266. $file->{'last'} = $file->{'value'};
  267. $file->{'value'} = 0;
  268. # Track available/unavailable status in each cycle
  269. {
  270. my $wasAvailable = $file->{'attr'}->{'available'};
  271. $file->{'attr'}->{'available'} = -r $file->{'path'} ? 1 : 0;
  272. if ($wasAvailable != $file->{'attr'}->{'available'}) {
  273. # Reset and extras for this file
  274. if (exists($EXTRAS{ $file->{'name'} })) {
  275. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  276. my $name = $file->{'name'} . '_' . $extra;
  277. $files{$name}{'last'} = $files{$name}{'value'};
  278. $files{$name}{'value'} = 0;
  279. }
  280. }
  281. # Determine which display device we have (if any)
  282. if (exists($DISPLAY_DEVS{ $file->{'name'} })) {
  283. $DISPLAY = $file->{'name'};
  284. if ($DEBUG) {
  285. print STDERR 'Selecting display device: ' . $DISPLAY . "\n";
  286. }
  287. }
  288. if ($DEBUG) {
  289. if ($file->{'attr'}->{'available'}) {
  290. print STDERR 'Added file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  291. } else {
  292. print STDERR 'Dropped file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  293. }
  294. }
  295. }
  296. }
  297. # Skip unavailable files
  298. if (!$file->{'attr'}->{'available'}) {
  299. next;
  300. }
  301. # Record the last update for MTIME files
  302. if ($file->{'attr'}->{'mtime'}) {
  303. my $mtime = mtime($file->{'path'});
  304. # All EXISTS files have MTIME set, and mtime returns 0 if the file does not exist, so we can overload this check
  305. if ($file->{'attr'}->{'exists'}) {
  306. if ($mtime > 0) {
  307. $file->{'update'} = $mtime;
  308. $file->{'value'} = 1;
  309. } elsif ($file->{'last'}) {
  310. $file->{'update'} = time();
  311. }
  312. } else {
  313. $file->{'update'} = $mtime;
  314. }
  315. if ($DEBUG) {
  316. print STDERR 'Mtime: ' . $file->{'name'} . ': ' . $file->{'value'} . ':' . $file->{'update'} . "\n";
  317. }
  318. }
  319. # Grab the state from STATUS files
  320. if ($file->{'attr'}->{'status'}) {
  321. my $text = '';
  322. {
  323. if (!open(my $fh, $file->{'path'})) {
  324. warn('Unable to open ' . $file->{'path'} . "\n");
  325. } else {
  326. local $/;
  327. $text = <$fh>;
  328. close($fh);
  329. }
  330. }
  331. # Parse the value for the file
  332. if ($file->{'attr'}->{'value'}) {
  333. $text =~ s/\n$//;
  334. $file->{'value'} = $text;
  335. } elsif ($file->{'attr'}->{'playing'}) {
  336. if ($text =~ /^playing:1/m) {
  337. $file->{'value'} = 1;
  338. }
  339. } else {
  340. if ($text =~ /1/) {
  341. $file->{'value'} = 1;
  342. }
  343. }
  344. if ($DEBUG) {
  345. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'value'} . "\n";
  346. }
  347. # Handle extras, if any
  348. if (exists($EXTRAS{ $file->{'name'} })) {
  349. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  350. my $name = $file->{'name'} . '_' . $extra;
  351. $files{$name}{'last'} = $files{$name}{'value'};
  352. $files{$name}{'value'} = 0;
  353. $files{$name}{'update'} = $file->{'update'};
  354. if ($text =~ $EXTRAS{ $file->{'name'} }{$extra}) {
  355. $files{$name}{'value'} = $1;
  356. }
  357. if ($DEBUG) {
  358. print STDERR 'Status (extra): ' . $name . ': ' . $files{$name}{'value'} . "\n";
  359. }
  360. }
  361. }
  362. }
  363. }
  364. # Simulate the old GUI indicator
  365. {
  366. my $gui = 0;
  367. if (exists($files{'PLAYING_WINDOW'}) && $files{'PLAYING_WINDOW'}->{'value'} ne 'Fullscreen video') {
  368. $gui = 1;
  369. }
  370. $files{'GUI'}->{'value'} = $gui;
  371. }
  372. if (exists($files{'PLAYING'})) {
  373. $files{'GUI'}->{'update'} = $files{'PLAYING'}->{'update'};
  374. }
  375. # Ignore the MOTION file if NO_MOTION is set
  376. if (exists($files{'NO_MOTION'}) && $files{'NO_MOTION'}->{'value'}) {
  377. if (exists($files{'MOTION'})) {
  378. $files{'MOTION'}->{'value'} = 0;
  379. $files{'MOTION'}->{'update'} = 0;
  380. }
  381. }
  382. # Set the global update timestamp, excluding files marked NOUPDATE
  383. foreach my $file (values(%files)) {
  384. if ($file->{'update'} > $updateLast && !$file->{'attr'}->{'no_update'}) {
  385. $updateLast = $file->{'update'};
  386. }
  387. }
  388. $timeSinceUpdate = time() - $updateLast;
  389. # Calculate the PLEX state
  390. $files{'PLEX'}->{'last'} = $files{'PLEX'}->{'value'};
  391. $files{'PLEX'}->{'value'} = 0;
  392. if (exists($files{'FRONT_APP'})) {
  393. if ( $files{'FRONT_APP'}->{'value'} =~ 'com.plexapp.plexhometheater'
  394. || $files{'FRONT_APP'}->{'value'} eq 'com.apple.ScreenSaver.Engine')
  395. {
  396. $files{'PLEX'}->{'value'} = 1;
  397. }
  398. }
  399. if ($files{'PLEX'}->{'last'} != $files{'PLEX'}->{'value'}) {
  400. $files{'PLEX'}->{'update'} = time();
  401. }
  402. # Determine some intermediate state data
  403. my $playing = 0;
  404. if (exists($files{'PLAYING'}) && $files{'PLAYING'}->{'value'}) {
  405. $playing = 1;
  406. }
  407. my $video = 0;
  408. if (exists($files{'PLAYING_TYPE'}) && $files{'PLAYING_TYPE'}->{'value'} ne 'audio') {
  409. $video = 1;
  410. } elsif (!exists($files{'PLAYING_TYPE'})) {
  411. $video = 1;
  412. }
  413. # Non-plex apps are always "playing" and "video"
  414. if (exists($files{'PLEX'}) && !$files{'PLEX'}->{'value'}) {
  415. $playing = 1;
  416. $video = 1;
  417. }
  418. # Calculate the new state
  419. $stateLast = $state;
  420. if (!defined($DISPLAY) || !exists($files{$DISPLAY})) {
  421. # If there's no display the state is always PLAY or PAUSE, as indicated by the master
  422. if ($playing) {
  423. $state = 'PLAY';
  424. } else {
  425. $state = 'PAUSE';
  426. }
  427. } elsif ($files{$DISPLAY}->{'value'}) {
  428. # If a display exists and is on:
  429. # PLAY when video is active and playing
  430. # PAUSE any other time (including when audio is active)
  431. if ($playing && $video) {
  432. $state = 'PLAY';
  433. } else {
  434. $state = 'PAUSE';
  435. }
  436. } else {
  437. # If the display exists but is off, check the timeouts to determine MOTION vs. OFF
  438. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  439. $state = 'OFF';
  440. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  441. $state = 'MOTION';
  442. }
  443. }
  444. if ($state eq 'INIT') {
  445. $state = 'OFF';
  446. }
  447. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  448. foreach my $file (values(%files)) {
  449. if ( $file->{'attr'}->{'clear_off'}
  450. && $file->{'value'}
  451. && $state eq 'OFF')
  452. {
  453. unlink($file->{'path'});
  454. $file->{'status'} = 0;
  455. if ($DEBUG) {
  456. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  457. }
  458. }
  459. }
  460. # Clear EXISTS_TIMEOUT files when the main state is "OFF" and EXISTS_TIMEOUT has expired (and before we append their status)
  461. foreach my $file (values(%files)) {
  462. if ( $file->{'attr'}->{'clear_timeout'}
  463. && $file->{'value'}
  464. && $state eq 'OFF'
  465. && $timeSinceUpdate > $EXISTS_TIMEOUT)
  466. {
  467. unlink($file->{'path'});
  468. $file->{'status'} = 0;
  469. if ($DEBUG) {
  470. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  471. }
  472. }
  473. }
  474. # Calculate the new status
  475. $statusLast = $status;
  476. {
  477. my @statTime = ();
  478. foreach my $file (values(%files)) {
  479. my $text = $file->{'value'};
  480. $text =~ s/\s/ /g;
  481. $text =~ s/\|/-/g;
  482. push(@statTime, $file->{'name'} . '|' . $text . '|' . $file->{'update'});
  483. }
  484. $status = "\n" . join("\n", @statTime);
  485. }
  486. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  487. foreach my $file (values(%files)) {
  488. if ($file->{'attr'}->{'clear'} && $file->{'value'}) {
  489. unlink($file->{'path'});
  490. $file->{'status'} = 0;
  491. if ($DEBUG) {
  492. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  493. }
  494. }
  495. }
  496. # Force updates on a periodic basis
  497. if (time() - $pushLast > $PUSH_TIMEOUT) {
  498. $update = 1;
  499. }
  500. # Update on any status change
  501. foreach my $file (values(%files)) {
  502. if ($file->{'value'} ne $file->{'last'}) {
  503. $update = 1;
  504. last;
  505. }
  506. }
  507. # Force updates on any state change
  508. if ($stateLast ne $state || $statusLast ne $status) {
  509. if ($DEBUG) {
  510. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  511. }
  512. $update = 1;
  513. }
  514. # Push the update
  515. if ($update) {
  516. # Note the push
  517. $pushLast = time();
  518. # Send notifications to all subscribers
  519. foreach my $sub (@subscribers) {
  520. # Drop subscribers that are not available
  521. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  522. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  523. my @new_subscribers = ();
  524. foreach my $new (@subscribers) {
  525. if ($new->{'socket'} eq $sub->{'socket'}) {
  526. next;
  527. }
  528. push(@new_subscribers, $new);
  529. }
  530. @subscribers = @new_subscribers;
  531. }
  532. }
  533. # Save the state and value to disk
  534. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  535. print $fh $state . "\n";
  536. close($fh);
  537. rename($tmp, $DATA_DIR . 'STATE');
  538. }
  539. }
  540. sub mtime($) {
  541. my ($file) = @_;
  542. my $mtime = 0;
  543. if (-r $file) {
  544. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  545. }
  546. return $mtime;
  547. }