state.pl 14 KB

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