state.pl 15 KB

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