state.pl 14 KB

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