state.pl 13 KB

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