state.pl 15 KB

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