state.pl 14 KB

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