state.pl 15 KB

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